package com.jhgsys.internal.hazard.controller;

import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.hazard.dto.HazardExamineTeamDto;
import com.jhgsys.internal.hazard.entity.HazardExamineTeam;
import com.jhgsys.internal.hazard.entity.HazardExamineTeamUser;
import com.jhgsys.internal.hazard.service.IHazardExamineTeamService;
import com.jhgsys.internal.hazard.service.IHazardExamineTeamUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *  Controller
 *
 * @author zhangwei
 * @date 2024-09-02 11:25:48
 */
@Slf4j
@Validated
@Controller
public class HazardExamineTeamController extends BaseController {

    @Autowired
    private IHazardExamineTeamService hazardExamineTeamService;
    @Autowired
    private IHazardExamineTeamUserService hazardExamineTeamUserService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardExamineTeam")
    @RequiresPermissions("hazardExamineTeam:view")
    public String hazardExamineTeamIndex(Model model){
        setModelAttribute(model);
        return FebsUtil.view("hazard/hazardExamineTeam/hazardExamineTeamList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardExamineTeam/add")
    @RequiresPermissions("hazardExamineTeam:add")
    public String hazardExamineTeamAdd(){
        return FebsUtil.view("hazard/hazardExamineTeam/hazardExamineTeamEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardExamineTeam/update/{id}")
    @RequiresPermissions("hazardExamineTeam:edit")
    public String hazardExamineTeamUpdate(Model model, @PathVariable("id") String id){
        model.addAttribute("hazardExamineTeam", hazardExamineTeamService.findHazardExamineTeamById(id));
        return FebsUtil.view("hazard/hazardExamineTeam/hazardExamineTeamEdit");
    }

    /**
     * 查询（所有）
     * @author zhangwei
     * @date 2024-09-02 11:25:48
     */
    @GetMapping("hazardExamineTeam")
    @ResponseBody
    @RequiresPermissions("hazardExamineTeam:view")
    public FebsResponse getAllHazardExamineTeams(HazardExamineTeam hazardExamineTeam) {
        return new FebsResponse().success().data(hazardExamineTeamService.findHazardExamineTeamList(hazardExamineTeam));
    }

    /**
     * 查询（分页）
     * @author zhangwei
     * @date 2024-09-02 11:25:48
     */
    @GetMapping("hazardExamineTeam/list")
    @ResponseBody
    @RequiresPermissions("hazardExamineTeam:view")
    public FebsResponse hazardExamineTeamList(QueryRequest request, HazardExamineTeamDto hazardExamineTeamDto) {
        Map<String, Object> dataTable = getDataTable(this.hazardExamineTeamService.findHazardExamineTeamPage(request, hazardExamineTeamDto));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 新增 HazardExamineTeam
     * @author zhangwei
     * @date 2024-09-02 11:25:48
     */
    @Log("新增HazardExamineTeam")
    @PostMapping("hazardExamineTeam")
    @ResponseBody
    @RequiresPermissions("hazardExamineTeam:add")
    public FebsResponse addHazardExamineTeam(@RequestBody HazardExamineTeamDto hazardExamineTeamDto) throws FebsException {
        try {
            checkNecessaryColumns(hazardExamineTeamDto,false);
            hazardExamineTeamDto.setCreatedBy(getCurrentUser().getUserName());
            this.hazardExamineTeamService.createHazardExamineTeam(hazardExamineTeamDto);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增HazardExamineTeam失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 逻辑删除 HazardExamineTeam
     * @author zhangwei
     * @date 2024-09-02 11:25:48
     */
    @Log("逻辑删除HazardExamineTeam")
    @GetMapping("hazardExamineTeam/delete/{id}")
    @ResponseBody
    @RequiresPermissions("hazardExamineTeam:delete")
    public FebsResponse deleteHazardExamineTeam(@PathVariable("id") String hazardExamineTeamIds) throws FebsException {
        try {
            HazardExamineTeam hazardExamineTeam = new HazardExamineTeam();
            hazardExamineTeam.setDeletedBy(getCurrentUser().getUserName());
            hazardExamineTeam.setDeletedTime(new Date());
            hazardExamineTeam.setDeletedFlg(FebsConstant.INVALID);
            this.hazardExamineTeamService.deleteHazardExamineTeam(hazardExamineTeam,hazardExamineTeamIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除HazardExamineTeam失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
    * 物理删除 HazardExamineTeam
    * @author zhangwei
    * @date 2024-09-02 11:25:48
    */
    @Log("物理删除HazardExamineTeam")
    @GetMapping("hazardExamineTeam/physicallyDelete/{id}")
    @ResponseBody
    @RequiresPermissions("hazardExamineTeam:delete")
    public FebsResponse physicallyDeleteHazardExamineTeam(@PathVariable("id") String hazardExamineTeamIds) throws FebsException {
        try {
            this.hazardExamineTeamService.physicallyDeleteHazardExamineTeam(hazardExamineTeamIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除HazardExamineTeam失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 修改 HazardExamineTeam
     * @author zhangwei
     * @date 2024-09-02 11:25:48
     */
    @Log("修改HazardExamineTeam")
    @PostMapping("hazardExamineTeam/update")
    @ResponseBody
    @RequiresPermissions("hazardExamineTeam:edit")
    public FebsResponse updateHazardExamineTeam(@RequestBody HazardExamineTeamDto hazardExamineTeamDto) throws FebsException {
        try {
            if(null!=hazardExamineTeamDto.getEditStatus() && !hazardExamineTeamDto.getEditStatus()){
                checkNecessaryColumns(hazardExamineTeamDto,true);
            }

            hazardExamineTeamDto.setUpdatedBy(getCurrentUser().getUserName());
            this.hazardExamineTeamService.updateHazardExamineTeam(hazardExamineTeamDto);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改HazardExamineTeam失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    private void setModelAttribute(Model model){
        model.addAttribute("tenantList", getTenantList());
        model.addAttribute("tenantId", getCurrentTenantId());
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
    }

    /**
     * 保存/编辑组内人员
     * @author dinghaitao
     * @date 2024-09-02 17:06:50
     */
    private void saveTeamUsers(HazardExamineTeamDto hazardExamineTeamDto){
        //先删除，再保存
        hazardExamineTeamUserService.deleteByTeamIds(hazardExamineTeamDto.getExamineTeamId());
        if(CollectionUtils.isNotEmpty(hazardExamineTeamDto.getTeamUserList())){
            List<HazardExamineTeamUser> teamUserList = hazardExamineTeamDto.getTeamUserList().stream()
                    .map(d -> {
                        HazardExamineTeamUser hazardExamineTeamUser = BeanHelper.copyProperties(d,HazardExamineTeamUser.class);
                        hazardExamineTeamUser.setExamineTeamId(hazardExamineTeamDto.getExamineTeamId());
                        hazardExamineTeamUser.setCreatedBy(getCurrentUserId());
                        hazardExamineTeamUser.setCreatedTime(new Date());
                        hazardExamineTeamUser.setTenantId(hazardExamineTeamDto.getTenantId());
                        return hazardExamineTeamUser;
                    }).collect(Collectors.toList());
            hazardExamineTeamUserService.saveBatch(teamUserList);
        }
    }

    /**
     * 新增/编辑保存时，字段必填项校验
     * @author dinghaitao
     * @date 2024-09-02 17:06:50
     */
    public void checkNecessaryColumns(HazardExamineTeamDto hazardExamineTeamDto,boolean editFlg) throws FebsException {
        if(editFlg && StringUtils.isEmpty(hazardExamineTeamDto.getExamineTeamId())){
            throw new FebsException("主键不能为空");
        } else if(StringUtils.isEmpty(hazardExamineTeamDto.getTeamName())){
            throw new FebsException("小组名称不能为空");
        } else if(null ==hazardExamineTeamDto.getSort()){
            throw new FebsException("小组排序不能为空");
        } else if(CollectionUtils.isEmpty(hazardExamineTeamDto.getTeamUserList())){
            throw new FebsException("请选择小组成员");
        }
    }

}
